<template>
  <div class="type-container">
    <el-card>
      <div class="management-title">
        <h2>户型管理 - {{ buildingName }} ({{ plotName }})</h2>
        <el-button @click="goBack" style="margin-left: 16px;">返回楼栋列表</el-button>
      </div>

      <!-- 操作按钮区域 -->
      <div class="type-header">
        <div class="header-left">
          <el-button type="primary" @click="handleAddType">
            <el-icon><Plus /></el-icon>
            新增户型
          </el-button>
          <el-button type="danger" @click="handleBatchDelete" :disabled="selectedTypes.length === 0">
            <el-icon><Delete /></el-icon>
            批量删除 ({{ selectedTypes.length }})
          </el-button>
        </div>
        <div class="header-right">
          <span class="type-count">共 {{ typeList.length }} 种户型</span>
        </div>
      </div>

      <!-- 户型网格 -->
      <div class="type-grid" v-loading="loading">
        <div 
          v-for="type in typeList" 
          :key="type.id"
          class="type-card"
          :class="{ 'selected': selectedTypes.includes(type.id) }"
          @click="handleTypeClick(type)"
        >
          <div class="type-header">
            <div class="type-title">
              <h3>{{ type.name }}</h3>
              <el-checkbox 
                v-model="selectedTypes" 
                :label="type.id" 
                @click.stop
                style="margin-left: 8px;"
              />
            </div>
          </div>
          
          <div class="type-image-section">
            <div v-if="type.imageUrl" class="type-image">
              <img :src="type.imageUrl" :alt="type.name" @error="handleImageError" />
            </div>
            <div v-else class="no-image" @click.stop="handleUploadImage(type)">
              <el-icon size="32"><Picture /></el-icon>
              <p>点击上传户型图</p>
            </div>
          </div>
          
          <div class="type-info">
            <div class="info-grid">
              <div class="info-item">
                <span class="info-label">面积：</span>
                <span class="info-value">{{ type.area || 0 }}㎡</span>
              </div>
              <div class="info-item">
                <span class="info-label">房间：</span>
                <span class="info-value">{{ type.roomNum || 0 }}室</span>
              </div>
              <div class="info-item">
                <span class="info-label">客厅：</span>
                <span class="info-value">{{ type.hallNum || 0 }}厅</span>
              </div>
              <div class="info-item">
                <span class="info-label">卫生间：</span>
                <span class="info-value">{{ type.toiletNum || 0 }}卫</span>
              </div>
              <div class="info-item">
                <span class="info-label">阳台：</span>
                <span class="info-value">{{ type.balconyNum || 0 }}阳台</span>
              </div>
              <div class="info-item">
                <span class="info-label">朝向：</span>
                <span class="info-value">{{ type.orientation || '暂无' }}</span>
              </div>
            </div>
          </div>
          
          <div class="type-description" v-if="type.description">
            <p>{{ type.description }}</p>
          </div>
          
          <div class="type-actions">
            <el-button size="small" type="primary" @click.stop="handleEditType(type)">
              编辑
            </el-button>
            <el-button size="small" type="success" @click.stop="handleUploadImage(type)">
              上传图片
            </el-button>
            <el-button size="small" type="danger" @click.stop="handleDeleteType(type)">
              删除
            </el-button>
          </div>
        </div>
        
        <!-- 空状态 -->
        <div v-if="!loading && typeList.length === 0" class="empty-type">
          <el-empty description="暂无户型数据">
            <el-button type="primary" @click="handleAddType">添加户型</el-button>
          </el-empty>
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑户型对话框 -->
    <el-dialog
      :title="isEdit ? '编辑户型' : '新增户型'"
      v-model="dialogVisible"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        label-position="right"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="户型名称" prop="name">
              <el-input v-model="formData.name" placeholder="如：三室两厅一卫" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="建筑面积" prop="area">
              <el-input v-model="formData.area" placeholder="请输入面积">
                <template #suffix>㎡</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="房间数" prop="roomNum">
              <el-input-number v-model="formData.roomNum" :min="0" :max="10" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客厅数" prop="hallNum">
              <el-input-number v-model="formData.hallNum" :min="0" :max="5" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="卫生间数" prop="toiletNum">
              <el-input-number v-model="formData.toiletNum" :min="0" :max="5" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="阳台数" prop="balconyNum">
              <el-input-number v-model="formData.balconyNum" :min="0" :max="5" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="朝向" prop="orientation">
          <el-select v-model="formData.orientation" placeholder="请选择朝向" style="width: 100%">
            <el-option label="南" value="南" />
            <el-option label="北" value="北" />
            <el-option label="东" value="东" />
            <el-option label="西" value="西" />
            <el-option label="东南" value="东南" />
            <el-option label="西南" value="西南" />
            <el-option label="东北" value="东北" />
            <el-option label="西北" value="西北" />
            <el-option label="南北" value="南北" />
            <el-option label="东西" value="东西" />
          </el-select>
        </el-form-item>

        <el-form-item label="户型描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入户型描述" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '更新' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片上传对话框 -->
    <el-dialog
      title="上传户型图"
      v-model="uploadDialogVisible"
      width="500px"
      :before-close="handleUploadDialogClose"
    >
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        drag
        :action="uploadAction"
        :headers="uploadHeaders"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        :limit="1"
        accept="image/*"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传jpg/png文件，且不超过2MB
          </div>
        </template>
      </el-upload>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleUploadDialogClose">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElForm } from 'element-plus';
import { Plus, Delete, Picture, UploadFilled } from '@element-plus/icons-vue';
import baseService from "@/service/baseService";

// 响应式数据
const loading = ref(false);
const typeList = ref<any[]>([]);
const selectedTypes = ref<number[]>([]);

// 对话框相关
const dialogVisible = ref(false);
const uploadDialogVisible = ref(false);
const submitLoading = ref(false);
const isEdit = ref(false);
const formRef = ref<InstanceType<typeof ElForm>>();
const uploadRef = ref();
const currentUploadType = ref<any>(null);

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  buildingId: null,
  area: '',
  roomNum: 0,
  hallNum: 0,
  toiletNum: 0,
  balconyNum: 0,
  orientation: '',
  description: ''
});

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入户型名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请输入建筑面积', trigger: 'blur' }
  ],
  roomNum: [
    { required: true, message: '请输入房间数', trigger: 'blur' }
  ]
};

// 获取URL参数（兼容hash模式）
const getUrlParams = () => {
  const hash = window.location.hash;
  const queryString = hash.includes('?') ? hash.split('?')[1] : window.location.search.substring(1);
  return new URLSearchParams(queryString);
};

const urlParams = getUrlParams();
const buildingId = ref(urlParams.get('buildingId') || '');
const buildingName = ref(decodeURIComponent(urlParams.get('buildingName') || ''));
const plotName = ref(decodeURIComponent(urlParams.get('plotName') || ''));

// 上传配置
const uploadAction = ref('/api/upload/image');
const uploadHeaders = ref({
  'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
});

// 图片加载错误处理
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  img.src = '';
};

// API调用函数
const getTypeList = async () => {
  loading.value = true;
  try {
    const response = await baseService.get(`/rental/areaplottype/getTypeByBuildingId/${buildingId.value}`);
    if (response.code === 0) {
      typeList.value = response.data.list || [];
    } else {
      ElMessage.error(response.msg || '获取户型列表失败');
    }
  } catch (error) {
    console.error('获取户型列表失败:', error);
    ElMessage.error('获取户型列表失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

const saveType = async (data: any) => {
  try {
    const response = await baseService.post('/rental/areaplottype', data);
    if (response.code === 0) {
      ElMessage.success('户型新增成功');
      return true;
    } else {
      ElMessage.error(response.msg || '新增失败');
      return false;
    }
  } catch (error) {
    console.error('新增户型失败:', error);
    ElMessage.error('新增失败，请检查网络连接');
    return false;
  }
};

const updateType = async (data: any) => {
  try {
    const response = await baseService.put('/rental/areaplottype', data);
    if (response.code === 0) {
      ElMessage.success('户型更新成功');
      return true;
    } else {
      ElMessage.error(response.msg || '更新失败');
      return false;
    }
  } catch (error) {
    console.error('更新户型失败:', error);
    ElMessage.error('更新失败，请检查网络连接');
    return false;
  }
};

const deleteType = async (id: number) => {
  try {
    const response = await baseService.delete(`/rental/areaplottype/${id}`);
    if (response.code === 0) {
      ElMessage.success('户型删除成功');
      return true;
    } else {
      ElMessage.error(response.msg || '删除失败');
      return false;
    }
  } catch (error) {
    console.error('删除户型失败:', error);
    ElMessage.error('删除失败，请检查网络连接');
    return false;
  }
};

const batchDeleteTypes = async (ids: number[]) => {
  try {
    const response = await baseService.delete('/rental/areaplottype/batch', { data: ids });
    if (response.code === 0) {
      ElMessage.success('批量删除成功');
      return true;
    } else {
      ElMessage.error(response.msg || '批量删除失败');
      return false;
    }
  } catch (error) {
    console.error('批量删除失败:', error);
    ElMessage.error('批量删除失败，请检查网络连接');
    return false;
  }
};

// 事件处理函数
const goBack = () => {
  window.close();
};

const handleTypeClick = (type: any) => {
  ElMessage.info(`点击了户型: ${type.name}`);
  console.log('户型信息:', type);
};

const resetForm = () => {
  Object.assign(formData, {
    id: null,
    name: '',
    buildingId: null,
    area: '',
    roomNum: 0,
    hallNum: 0,
    toiletNum: 0,
    balconyNum: 0,
    orientation: '',
    description: ''
  });
  formRef.value?.clearValidate();
};

const handleAddType = () => {
  isEdit.value = false;
  resetForm();
  formData.buildingId = buildingId.value;
  dialogVisible.value = true;
};

const handleEditType = (type: any) => {
  isEdit.value = true;
  Object.assign(formData, {
    id: type.id,
    name: type.name,
    buildingId: type.buildingId,
    area: type.area,
    roomNum: type.roomNum,
    hallNum: type.hallNum,
    toiletNum: type.toiletNum,
    balconyNum: type.balconyNum,
    orientation: type.orientation,
    description: type.description
  });
  dialogVisible.value = true;
};

const handleDeleteType = async (type: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除户型"${type.name}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const success = await deleteType(type.id);
    if (success) {
      getTypeList();
    }
  } catch {
    ElMessage.info('已取消删除');
  }
};

const handleBatchDelete = async () => {
  if (selectedTypes.value.length === 0) {
    ElMessage.warning('请选择要删除的户型');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedTypes.value.length} 个户型吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const success = await batchDeleteTypes(selectedTypes.value);
    if (success) {
      selectedTypes.value = [];
      getTypeList();
    }
  } catch {
    ElMessage.info('已取消删除');
  }
};

const handleDialogClose = () => {
  dialogVisible.value = false;
  resetForm();
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    submitLoading.value = true;

    let success = false;
    if (isEdit.value) {
      success = await updateType(formData);
    } else {
      success = await saveType(formData);
    }

    if (success) {
      dialogVisible.value = false;
      resetForm();
      getTypeList();
    }
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    submitLoading.value = false;
  }
};

// 图片上传相关
const handleUploadImage = (type: any) => {
  currentUploadType.value = type;
  uploadDialogVisible.value = true;
};

const handleUploadDialogClose = () => {
  uploadDialogVisible.value = false;
  currentUploadType.value = null;
  uploadRef.value?.clearFiles();
};

const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

const handleUploadSuccess = async (response: any) => {
  if (response.code === 0 && currentUploadType.value) {
    // 更新户型图片
    const updateData = {
      id: currentUploadType.value.id,
      imageUrl: response.data.url
    };

    const success = await updateType(updateData);
    if (success) {
      uploadDialogVisible.value = false;
      currentUploadType.value = null;
      getTypeList();
    }
  } else {
    ElMessage.error(response.msg || '图片上传失败');
  }
};

const handleUploadError = () => {
  ElMessage.error('图片上传失败，请重试');
};

// 初始化
onMounted(() => {
  if (!buildingId.value) {
    ElMessage.error('缺少楼栋ID参数');
    return;
  }
  getTypeList();
});
</script>
